package leetcode.day_2021_3_1_2022_3_7;

import java.util.ArrayList;
import java.util.List;

/**
 * 39. 组合总和
 * https://leetcode-cn.com/problems/combination-sum/
 */
public class LeetCode0039 {

    static List<List<Integer>> res = new ArrayList<>();

    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        solve(candidates, target, new ArrayList<>(), 0, 0);
        return res;
    }

    public static void solve(int[] candidates, int target, List<Integer> list, int sum, int begin) {
        if (target == sum) {
            res.add(new ArrayList<>(list));
            return;
        }

        for (int i=begin; i<candidates.length; i++) {
            if (sum+candidates[i] - target > 0) continue;
            list.add(candidates[i]);
            sum += candidates[i];
            solve(candidates, target, list, sum, i);
            list.remove(list.size()-1);
            sum -= candidates[i];
        }
    }

    public static void main(String[] args) {
        System.out.println(combinationSum(new int[]{2, 3, 5}, 8));
    }
}
